<template>
  <div class="contract-container">
    <!-- 顶部导航区域 -->
    <div class="header-wrapper">
      <!-- 顶部导航 -->
      <div class="header">
        <van-icon name="arrow-left" class="back-icon" @click="goBack" />
        <div class="header-title">合同审批</div>
      </div>
    </div>

    <!-- 标签页 -->
    <van-tabs v-model:active="activeTab" class="contract-tabs">
      <!-- 发起提交标签页 -->
      <van-tab title="发起提交" name="submit">
        <ContractAdd />
      </van-tab>
      
      <!-- 查看数据标签页 -->
      <van-tab title="查看数据" name="view">
        <!-- 搜索框 -->
        <div class="search-container">
          <van-search
            v-model="searchValue"
            placeholder="搜索合同名称、编号"
            @search="onSearch"
            @input="onSearchInput"
          />
        </div>

        <!-- 筛选和新建按钮 -->
        <div class="filter-section">
          <div class="filter-buttons">
            <div class="filter-item" @click="showStatusFilter">
              <span>状态</span>
              <van-icon name="arrow-down" class="filter-arrow" />
            </div>
            <div class="filter-item" @click="showTypeFilter">
              <span>类型</span>
              <van-icon name="arrow-down" class="filter-arrow" />
            </div>
            <div class="filter-item" @click="showTimeFilter">
              <span>时间</span>
              <van-icon name="arrow-down" class="filter-arrow" />
            </div>
          </div>
        </div>

        <!-- 合同列表 -->
        <div class="contract-list">
          <div 
            v-for="contract in filteredContracts" 
            :key="contract.id" 
            class="contract-item"
            @click="viewContract(contract)"
          >
            <div class="contract-header">
              <div class="contract-title">{{ contract.name }}</div>
              <div class="contract-status" :class="getStatusClass(contract.status)">
                {{ getStatusText(contract.status) }}
              </div>
            </div>
            <div class="contract-info">
              <div class="info-row">
                <span class="label">合同编号:</span>
                <span class="value">{{ contract.number }}</span>
              </div>
              <div class="info-row">
                <span class="label">对方主体:</span>
                <span class="value">{{ contract.counterparty }}</span>
              </div>
              <div class="info-row">
                <span class="label">合同金额:</span>
                <span class="value amount">¥{{ formatAmount(contract.amount) }}</span>
              </div>
              <div class="info-row">
                <span class="label">签订时间:</span>
                <span class="value">{{ contract.signDate }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="filteredContracts.length === 0" class="empty-state">
          <div class="empty-icon">
            <img src="@/assets/homeOther/handle_bg.png" alt="无合同" />
          </div>
          <div class="empty-text">暂无合同数据</div>
        </div>

        <!-- 状态筛选 -->
        <van-action-sheet
          v-model:show="showStatusSheet"
          :actions="statusActions"
          title="选择状态"
          @select="onStatusSelect"
          cancel-text="取消"
        />

        <!-- 类型筛选 -->
        <van-action-sheet
          v-model:show="showTypeSheet"
          :actions="typeActions"
          title="选择类型"
          @select="onTypeSelect"
          cancel-text="取消"
        />

        <!-- 时间筛选 -->
        <van-action-sheet
          v-model:show="showTimeSheet"
          :actions="timeActions"
          title="选择时间范围"
          @select="onTimeSelect"
          cancel-text="取消"
        />
      </van-tab>
    </van-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import ContractAdd from './add.vue'
import { showToast } from 'vant'

// 路由实例
const router = useRouter()

// 当前活跃的标签页
const activeTab = ref('submit')

// 搜索关键词
const searchValue = ref('')

// 搜索建议
const searchSuggestions = ref<string[]>([])

// 筛选状态
const showStatusSheet = ref(false)
const showTypeSheet = ref(false)
const showTimeSheet = ref(false)

// 当前筛选条件
const currentFilters = reactive({
  status: '',
  type: '',
  timeRange: ''
})

// 合同数据类型
interface Contract {
  id: string
  name: string
  number: string
  counterparty: string
  amount: number
  signDate: string
  status: 'draft' | 'pending' | 'approved' | 'rejected' | 'executed'
  type: 'purchase' | 'sales' | 'service' | 'lease'
  createTime: string
}

// 模拟合同数据
const contracts = ref<Contract[]>([
  {
    id: '1',
    name: '软件开发服务合同',
    number: 'HT2024001',
    counterparty: '北京科技有限公司',
    amount: 500000,
    signDate: '2024-01-15',
    status: 'approved',
    type: 'service',
    createTime: '2024-01-10 10:00:00'
  },
  {
    id: '2',
    name: '设备采购合同',
    number: 'HT2024002',
    counterparty: '上海设备制造商',
    amount: 1200000,
    signDate: '2024-01-20',
    status: 'pending',
    type: 'purchase',
    createTime: '2024-01-18 14:30:00'
  },
  {
    id: '3',
    name: '办公室租赁合同',
    number: 'HT2024003',
    counterparty: '深圳物业管理公司',
    amount: 240000,
    signDate: '2024-02-01',
    status: 'executed',
    type: 'lease',
    createTime: '2024-01-25 09:15:00'
  }
])

// 状态选项
const statusActions = [
  { name: '全部状态', value: '' },
  { name: '草稿', value: 'draft' },
  { name: '待审批', value: 'pending' },
  { name: '已通过', value: 'approved' },
  { name: '已拒绝', value: 'rejected' },
  { name: '已执行', value: 'executed' }
]

// 类型选项
const typeActions = [
  { name: '全部类型', value: '' },
  { name: '采购合同', value: 'purchase' },
  { name: '销售合同', value: 'sales' },
  { name: '服务合同', value: 'service' },
  { name: '租赁合同', value: 'lease' }
]

// 时间选项
const timeActions = [
  { name: '全部时间', value: '' },
  { name: '今天', value: 'today' },
  { name: '本周', value: 'week' },
  { name: '本月', value: 'month' },
  { name: '本年', value: 'year' }
]

// 计算过滤后的合同列表
const filteredContracts = computed(() => {
  let result = contracts.value

  // 搜索过滤
  if (searchValue.value) {
    const keyword = searchValue.value.toLowerCase()
    result = result.filter(contract => 
      contract.name.toLowerCase().includes(keyword) ||
      contract.number.toLowerCase().includes(keyword)
    )
  }

  // 状态过滤
  if (currentFilters.status) {
    result = result.filter(contract => contract.status === currentFilters.status)
  }

  // 类型过滤
  if (currentFilters.type) {
    result = result.filter(contract => contract.type === currentFilters.type)
  }

  // 时间过滤
  if (currentFilters.timeRange) {
    const now = new Date()
    result = result.filter(contract => {
      const contractDate = new Date(contract.signDate)
      switch (currentFilters.timeRange) {
        case 'today':
          return contractDate.toDateString() === now.toDateString()
        case 'week':
          const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
          return contractDate >= weekAgo
        case 'month':
          return contractDate.getMonth() === now.getMonth() && 
                 contractDate.getFullYear() === now.getFullYear()
        case 'year':
          return contractDate.getFullYear() === now.getFullYear()
        default:
          return true
      }
    })
  }

  return result
})

// 返回上一页
const goBack = () => {
  router.back()
}

// 搜索
const onSearch = (value: string) => {
  console.log('搜索:', value)
}

// 搜索输入
const onSearchInput = (value: string) => {
  searchValue.value = value
  
  // 根据输入更新搜索建议
  if (value.trim()) {
    const suggestions = contracts.value
      .filter(contract => 
        contract.name.toLowerCase().includes(value.toLowerCase()) ||
        contract.number.toLowerCase().includes(value.toLowerCase())
      )
      .map(contract => contract.name)
      .slice(0, 5) // 最多显示5个建议
    
    searchSuggestions.value = [...new Set(suggestions)] // 去重
  } else {
    searchSuggestions.value = []
  }
}

// 选择搜索建议
const selectSuggestion = (suggestion: string) => {
  searchValue.value = suggestion
  searchSuggestions.value = []
  onSearch(suggestion)
}

// 显示状态筛选
const showStatusFilter = () => {
  showStatusSheet.value = true
}

// 显示类型筛选
const showTypeFilter = () => {
  showTypeSheet.value = true
}

// 显示时间筛选
const showTimeFilter = () => {
  showTimeSheet.value = true
}

// 状态选择
const onStatusSelect = (action: any) => {
  currentFilters.status = action.value
  showStatusSheet.value = false
}

// 类型选择
const onTypeSelect = (action: any) => {
  currentFilters.type = action.value
  showTypeSheet.value = false
}

// 时间选择
const onTimeSelect = (action: any) => {
  currentFilters.timeRange = action.value
  showTimeSheet.value = false
}
// 查看合同
const viewContract = (contract: Contract) => {
  router.push(`/contract/detail/${contract.id}`)
}

// 编辑合同
const editContract = (contract: Contract) => {
  router.push(`/contract/edit/${contract.id}`)
}

// 查看详情
const viewDetails = (contract: Contract) => {
  router.push(`/contract/detail/${contract.id}`)
}

// 获取状态样式类
const getStatusClass = (status: string) => {
  const statusMap: Record<string, string> = {
    'draft': 'status-draft',
    'pending': 'status-pending',
    'approved': 'status-approved',
    'rejected': 'status-rejected',
    'executed': 'status-executed'
  }
  return statusMap[status] || ''
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'draft': '草稿',
    'pending': '待审批',
    'approved': '已通过',
    'rejected': '已拒绝',
    'executed': '已执行'
  }
  return statusMap[status] || status
}

// 格式化金额
const formatAmount = (amount: number) => {
  return amount.toLocaleString()
}

// 页面初始化
onMounted(() => {
  console.log('合同管理页面已加载')
})
</script>

<style lang="scss" scoped>
@import url('./style/index.scss');
</style>